package com.gitee.simons.common.utils;

import com.gitee.simons.common.exception.ServiceException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Log4j2
public class HttpFileUtil {
	
	public static final String CONTENT_TYPE_FORM_DATA = "multipart/form-data";
	public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream";
	public static final String CONTENT_TYPE_JPG = "image/jpeg;";
	
	private HttpFileUtil(){
		//工具类，私有构造
	}

    /**
     * 文件通过流设置进response中
     * @param inputStream
     * @param contentType
     * @param srcFileName
     * @param response
     * @throws ServiceException
     */
	public static void setFileToResponse(InputStream inputStream, String contentType, String srcFileName,HttpServletResponse response) throws ServiceException {
		// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
		response.setContentType(contentType);
		// 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫test.pdf)
		String outputFileName = srcFileName;
		if (CONTENT_TYPE_FORM_DATA.equals(contentType) || CONTENT_TYPE_OCTET_STREAM.equals(contentType)) {
			try {
				outputFileName = URLEncoder.encode(srcFileName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				log.info("",e);
			}
		}
		
		int length = 0;
		try {
			length = inputStream.available();
		} catch (IOException e1) {
			log.error("", e1);
		}
		response.setHeader("Content-Disposition", "attachment;fileName=" + outputFileName);
		response.setHeader("Content-Length", String.valueOf(length));
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			IOUtils.copy(inputStream, out);
			out.flush();
		} catch (Exception e) {
			log.error("", e);
			throw new ServiceException(e.getMessage());
		} finally {
			IOUtils.closeQuietly(out);
		}
	}
}
